<?php

namespace Mvc;

use Mvc\config\ArrayAccess\Config;

/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-6-21
 * Time: 17:51
 * @description: 系统初始化
 * @Author: yfl
 * @QQ 554665488
 */
class Application
{
    public $base_dir;

    public $config;//配置对象

    protected static $instances;

    protected $decorators = [];

    public function __construct($base_dir)
    {

        $this->base_dir = $base_dir;
        $this->config = new Config($this->base_dir);
    }

    public static function instance($base_dir = '')
    {
        if (!isset(self::$instances)) {
            self::$instances = new self($base_dir);
        }
        return self::$instances;
    }

    public function dispatch()
    {
//        var_dump($_SERVER['REQUEST_URI']);
        $baseUrl = $_SERVER['REQUEST_URI'];
        list($controller, $action) = explode('/', trim($baseUrl, '/'));
        if (!isset($action)) $action = 'index'; //控制器默认执行的方法
        $RequestControllerName = strtolower($controller);
        $controller = ucwords($controller);
        $class = '\\Mvc\\App\\Controller\\' . $controller.'Controller';
        //实例化控制器
        $requestControllerObj = new $class($controller, $action);
        //获得控制器装饰器配置信息
        $getControllerInfo = $this->config['controller'];
        if (isset($getControllerInfo[$RequestControllerName]['decorator'])) {
            $decorator_config = $getControllerInfo[$RequestControllerName]['decorator'];//装饰器配置信息
            foreach ($decorator_config as $class) {
                $this->decorators[] = new $class;//实例化装饰器
            }
            //执行前置装饰器方法
            foreach ($this->decorators as $decorator) {
                $decorator->beforeAction($requestControllerObj);
            }
            //执行请求的方法
            var_dump($requestControllerObj);
            var_dump($action);
            $return_value = $requestControllerObj->$action();
            //执行后置装饰器方法
            foreach ($this->decorators as $decorator) {
                $decorator->afterAction($return_value);
            }
        }else{
            $requestControllerObj->$action();
        }
    }
}


